package org.rambadger.command.axon;

import com.mongodb.MongoClient;
import com.yammer.dropwizard.lifecycle.Managed;


/**
 * Assures DropWizard that we can access the database at startup time.
 * <p>
 *     This probably isn't necessary due to the way that the Java MongoDB driver works.
 *     The driver handles pooling, thread safety, and (re)establishing the connection in the background so it only matters if a connection to the database server can be established when the database actually gets accessed.
 * </p>
 * <p>
 *     There would likely be no issues if {@link #start()} were changed to to a no-op.
 * </p>
 */
public class MongoManager implements Managed {
    private final MongoClient mongo;

    /**
     * Creates a new MongoManager instance around the provided {@link MongoClient} instance.
     *
     * @param mongo the MongoClient instance
     */
    public MongoManager(MongoClient mongo) {
        this.mongo = mongo;
    }

    @Override
    public void start() throws Exception {
        /*
        Technique based on https://groups.google.com/d/msg/mongodb-user/6egdzjDJnFc/BMeiDJU9cdoJ
        An exception should be thrown if it can't access any of the configured databases
         */
        //This could easily be made a no-op
        mongo.getDatabaseNames();
    }

    @Override
    public void stop() throws Exception {
        mongo.close();
    }
}
